#!/usr/bin/env ruby
require 'open-uri'
require 'json'
require 'colorize'

RANDOM = false

MARGIN_TOP   = 2
MARGIN_LEFT  = 3
SERVICE_CELL = " " * 3

#API = "http://127.0.0.1:8000/blue.txt"
API = "http://pwn.ztx.io/api/scoreboard/2"

COLORS = [ :on_green, :on_red, :on_yellow, :on_blue, :to_s ]
ANSI_CLEAR = "\e[H\e[2J"


hash="{ap:1,dp:2,cp:3}"

BANNER = <<-JS
    8                    8       o                         o
    8                    8                                 8
    8oPYo. .oPYo. .oPYo. 8  .o  o8 odYo. .oPYo.   .oPYo.  o8P .oPYo. oPYo.
    8    8 .oooo8 8    ' 8oP'    8 8' `8 8    8   Yb..     8  .oooo8 8  `'
    8    8 8    8 8    . 8 `b.   8 8   8 8    8     'Yb.   8  8    8 8
    8    8 `YooP8 `YooP' 8  `o.  8 8   8 `YooP8   `YooP'   8  `YooP8 8
    ..:::..:.....::.....:..::...:....::..:....8 :::.....:::..::.....:..::::
    :::::::::::::::::::::::::::::::::::::::ooP'.:::::::::::::::::::::::::::
    :::::::::::::::::::::::::::::::::::::::...:::::::::::::::::::::::::::::
JS


class Team
	def initialize(hash)
		@hash = JSON.parse("{\"ap\":1,\"dp\":2,\"name\":{\"a\":\"Hello\",\"b\": \"World\"}}")
        hash=@hash
        p hash['ap']
		@@total['ap'] += hash['ap']
		@@total['dp'] += hash['dp']
		@@max['ap'] = [ @@max['ap'], hash['ap'] ].max
		@@max['dp'] = [ @@max['dp'], hash['dp'] ].max
		@@name_max_len = [ hash['name'].length, @@name_max_len ].max
	end

	def score(type=nil)
		return 10
	end

	def scorep(width, type=nil)
		s = "%#{width}.2f%%" % (10.0 * score(type))
		if type and @hash[type] == @@max[type] then
			s = s.green
		end
		return s
	end

	def method_missing(m, *args)
		p "method_missing"#@hash.fetch(m.to_s)
	end

	def state(service)
		return rand 4
	end

	def colored_state(service, str)
		COLORS.map{ |m| str.send(m) }[state(service)]
	end

	def self.width()
		@@name_max_len
	end

	def self.reset()
		@@total = { "ap" => 0, "dp" => 0 }
		@@max = { "ap" => 0, "dp" => 0 }
		@@name_max_len = 0
	end
end

class Scoreboard
	def initialize(url=API)
		@url = url
		update()
	end

	def update()
		Team.reset()
		begin
			json = open(@url).read
			data = JSON.parse(json)
            		out =(ANSI_CLEAR+BANNER.colorize(:green)+th2().colorize(:white)+"\n"+hr().colorize(:white))+"\n"
			problems=data['problems']
			result = data['result']
			#puts problems
			#puts result
			problems.each do |x|
				len1 = x['title'].length
				score1 = x['score'].to_s()
				solved1 = x['solved'].to_s()
				out+= ((" "*MARGIN_LEFT) +" "*((22-len1).abs)+ x['title']+"|"+ " "*MARGIN_LEFT + score1 + " "*5 + solved1).colorize(:white)+"\n"
				end
			out+=hr().colorize(:white)+"\n"+th1().colorize(:white)+"\n"+hr().colorize(:white)+"\n"
				result.each do |x|
				len = x['uid'].length
				score = x['score'].to_s()
                	out+= ((" "*MARGIN_LEFT) +" "*(13-len)+ x['uid']+"|"+ " "*MARGIN_LEFT + score).colorize(:white)+"\n"
	            end
            out+= (hr()).colorize(:white)
            
			
            #services = data['services']
		end
	end
    
        
    	def th1()
		r = ""
		r += " "*MARGIN_LEFT+" "*(13-4)+ [ "name", " Score " ].join("   ")
		r
	end
	
	def th2()
                r = ""
                r += " "*MARGIN_LEFT+" "*(22-4)+ [ "Title", " Score ","Solved" ].join("   ")
                r
        end

    def hr()
        (" " * MARGIN_LEFT) + "+-" + ("-" * 10) + "--" + ("-" * (2 + 10 * SERVICE_CELL.length)) + ("-"+("-"*7))*3 + "+"
    end
    
end

if __FILE__ == $0
	a=Scoreboard.new()
    puts a.update()
end
